package Server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.StringTokenizer;

import Client.LogLine;
import socket.SocketUtil;

/**
 * This class take a name string and scans the log file. Then,
 * return matched name value pairs as a string
 * Accomplish this task limited number of threads are used
 * which are taken from threadpool
 * @author Group6
 *
 */
public class NetworkServerTest extends NetworkServer implements Runnable {
	Socket server;

	public NetworkServerTest(Socket server, String serverName) {
		super(server, serverName);
	}

	/**
	 * At first file record lines are scanned and an array list is created
	 * for each line. Then, these lines are compared with the name string which sent
	 * from client. A new list with name value pairs is created and sent back to client
	 */
	public synchronized void run() {
		try {
			//File location
			String file = "files\\log.txt";
			//To create stream from file
			BufferedReader inFile = new BufferedReader(new FileReader(file));
			
			//String tokenizer to split each line
			StringTokenizer token;
			//An array list to contain each line
			ArrayList<LogLine> lineList = new ArrayList<LogLine>();
			
			String line;
			//Operation lasts until the end of the file
			while ((line = inFile.readLine()) != null) {
				LogLine logLine = new LogLine();

				//Each line cleared from special charecters such as <,>,:
				token = new StringTokenizer(line, "<>:");
				//if word count is 0 then its name
				//if word count is 1 then its value
				int wordCount = 0;
				while (token.hasMoreTokens()) {
					if (wordCount == 0)
						logLine.setName(token.nextToken());
					else if (wordCount == 1)
						logLine.setValue(Integer.parseInt(token.nextToken()));
					wordCount++;
				}
				lineList.add(logLine);
			}

			//To create stream from client
			BufferedReader in = SocketUtil.getReader(getServer());
			//Name string taken from client
			String message = in.readLine();

			//Comparing names and successful pairs added to list
			ArrayList<LogLine> containList = new ArrayList<LogLine>();
			for (LogLine logline : lineList) {
				if (logline.getName().equalsIgnoreCase(message))
					containList.add(logline);
			}

			//Sent size of the message
			PrintWriter out = SocketUtil.getWriter(getServer());
			out.println(containList.size());

			//Sent contain of the message as a single line
			for (LogLine logLine : containList) {
				out.println(logLine.getName() + ","
						+ Integer.toString(logLine.getValue()));
			}
			//Close reader and writer
			in.close();
			out.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
